Webservice入门教程 |
您所在的位置:网站首页 › apache CXF使用手册 › Webservice入门教程 |
场景 实现搭建服务端 1.打开Eclipse--新建Dynamic Project--CXF_Spring_Web 2.导入cxf的jar包 jar包位置: 将lib下的所有jar包文件导入,虽然不都用得到但是先暂时都导入。 然后右击lib包右击build path
3.新建接口以及实现类 在src下新建包,先在包下新建实体类 package com.badao.bean; public class Order { public int getId() { return id; } public void setId(int id) { this.id = id; } public Order(int id, String name, double price) { super(); this.id = id; this.name = name; this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } private int id; private String name; private double price; }然后在包下新建接口OrderWS package com.badao.cxf; import javax.jws.WebMethod; import javax.jws.WebService; import com.badao.bean.Order; @WebService public interface OrderWS { @WebMethod public Order getOrderById(int id); }接口上要添加注解@WebService 方法上要添加注解 @WebMethod 然后新建实现类 package com.badao.cxf; import javax.jws.WebService; import com.badao.bean.Order; @WebService public class OrderWSImpl implements OrderWS { @Override public Order getOrderById(int id) { System.out.println("服务端获取的id为:"+id); return new Order(id,"订单1",100000.0); } }接口实现上要添加注解@WebService 4.编写配置文件beans.xml 依据文档,需要编写一个beans.xml配置文件。
beans.xml代码: 5.修改web.xml 依据文档 web.xml代码: CXF_Spring_Web index.html index.htm index.jsp default.html default.htm default.jsp contextConfigLocation classpath:beans.xml org.springframework.web.context.ContextLoaderListener CXFServlet org.apache.cxf.transport.servlet.CXFServlet 1 CXFServlet /* 运行服务端将项目部署到Tomcat上。 打开浏览器访问: http://localhost:8080/CXF_Spring_Web/orderWS 查看wsdl文件 打开浏览器访问: http://localhost:8080/CXF_Spring_Web/orderWS?wsdl 至此则服务端部署完成。 服务端项目结构目录 1.新建项目 Eclipse新建Dynamic project 同上面一样导入jar包。 2.根据wsdl文档生成客户端代码 下载apache-cxf-2.5.9,在bin目录下有wsdl2java.bat 将其配置进环境变量。 进入到客户端的真实目录下的src下。 在此处打开cmd,输入: wsdl2java http://localhost:8080/CXF_Spring_Web/orderWS?wsdl可以生成客户端代码。 此时回到Eclipse 下刷新项目。
编写客户端配置文件 依据文档,在src下新建client-beans.xml 编写客户端代码 新建ClientTest.java package com.badao.test; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.badao.cxf.Order; import com.badao.cxf.OrderWS; public class ClientTest { public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"client-beans.xml"}); OrderWS orderWS = (OrderWS) context.getBean("orderClient"); Order order = orderWS.getOrderById(24); System.out.println("服务端返回的数据为:"+order.getId()+order.getName()+order.getPrice()); } }客户端项目结构目录 效果 将服务端代码部署到Tomcat上并运行,然后运行客户端的ClientTest方法。 客户端运行效果: 服务端效果: |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |